import React, { useEffect, useState } from 'react';
import moment from 'moment';
import { DatePicker, Form, Space, Button, Select, Radio } from 'antd';
import { AllIssuePlan } from '../index';
import { FileTextOutlined } from '#/utils/antdIcons.js';
import type { IFormValue, IDealElementOptions } from '../../type';
import styles from './index.less';
import { useDebounceFn } from 'ahooks';
import { TjSegmented } from '@/pages/ETrade/components/index.js';
import { specialProvinceValue } from '../../dictionary';

interface IProps {
  /**
   * 表单值
   */
  values: IFormValue;
  /**
   * 省份数据
   */
  provinceOptions?: IDealElementOptions[];
  /**
   * 改变省份
   */
  onChangeProvince?: (params: IFormValue) => void;
  /**
   * 搜索数据
   */
  onSearch?: (values: IFormValue) => void;
  /**
   * 默认请求
   */
  defaultRequest?: (data: any) => void;
  /**
   * 重置调整策略编辑
   */
  strategyOnReset?: () => void;
}

const Header = (props: IProps) => {
  const { values = {}, provinceOptions = [], onSearch, defaultRequest, strategyOnReset } = props;
  const [form] = Form.useForm();
  const [visible, setVisible] = useState<boolean>(false);
  const [stationOptions, setStationOptions] = useState<any>(provinceOptions?.[0]?.children || []);
  const [provinceName, setProvinceName] = useState<any>();
  const [stationName, setStationName] = useState<any>();
  const [quantityQuotationHidden, setQuantityQuotationHidden] = useState<boolean>(true);
  // 数据类型（仅山西）
  const [saveType, setSaveType] = useState<any>(1);

  useEffect(() => {
    const { calendarDate, ...rest }: any = values;
    const _values = {
      calendarDate: moment(calendarDate),
      ...rest,
    };
    form && form.setFieldsValue(_values);
    // 目前只有山西新疆存在报量报价
    // if (_values.marketId === 'PHBSX' || _values.marketId === 'PXBXJ') {
    if (_values.marketId === 'PXBXJ') {
      setQuantityQuotationHidden(false);
    } else {
      setQuantityQuotationHidden(true);
    }
  }, [values]);

  // 修改数据来源
  const changeSaveType = (e: any) => {
    setSaveType(e.target.value);
    const data = form.getFieldsValue();
    const obj = { ...data, saveType: e.target.value };
    onFinish(obj);
  };

  // 改变省份
  const _onChangeProvince = (
    e: string,
    { provinceId, children, provinceName, stationName }: any,
  ) => {
    form.setFieldsValue({
      marketId: e,
      provinceId,
      stationId: children[0]?.value,
    });
    // 目前只有山西新疆存在报量报价
    // if (e === 'PHBSX' || e === 'PXBXJ') {
    if (e === 'PXBXJ') {
      setQuantityQuotationHidden(false);
    } else {
      setQuantityQuotationHidden(true);
      form.setFieldsValue({
        quantityQuotation: 1,
      });
    }
    setStationOptions(children);
    setProvinceName(provinceName);
    setStationName(stationName);
  };

  const filterOption = (input: string, option: { value: any; label: any }) => {
    const { label } = option;
    return label?.toLowerCase().indexOf(input.toLowerCase()) >= 0;
  };

  // 搜索
  const onFinish = (data: IFormValue) => {
    const { calendarDate } = data;
    const _calendarDate = moment(calendarDate).format('YYYY-MM-DD');

    const _params = {
      ...data,
      calendarDate: _calendarDate,
      provinceName,
      stationName,
      ...{ ...(data.hasOwnProperty('saveType') ? {} : { saveType }) },
    };
    onSearch && onSearch(_params);
  };

  // 申报总览
  const onClick = () => {
    if (provinceOptions.length > 0) {
      setVisible(true);
    }
  };

  // 关闭
  const onClose = () => {
    setVisible(false);
  };
  const _onReset = useDebounceFn(
    () => {
      setStationOptions(provinceOptions?.[0]?.children || []);
      defaultRequest && defaultRequest(provinceOptions);
      strategyOnReset && strategyOnReset();
    },
    { wait: 500 },
  );
  return (
    <div className={styles.container}>
      <Form
        form={form}
        name="filter"
        requiredMark={false}
        colon={false}
        autoComplete="off"
        onFinish={onFinish}
      >
        <Form.Item name="marketId" rules={[{ required: true, message: '请选择省份' }]}>
          <Select
            placeholder={'请选择省份'}
            showArrow={true}
            style={{ width: 200 }}
            key="value"
            options={provinceOptions as any[]}
            showSearch={true}
            filterOption={filterOption as any}
            onChange={_onChangeProvince}
          />
        </Form.Item>
        <Form.Item noStyle name="provinceId" rules={[{ required: true, message: '请选择省份' }]} />
        <Form.Item name="stationId" rules={[{ required: true, message: '请选择交易单元' }]}>
          <Select
            style={{ width: 200 }}
            placeholder="请选择"
            showArrow={true}
            options={(stationOptions || []) as any}
            showSearch={true}
            filterOption={filterOption as any}
          />
        </Form.Item>
        <Form.Item name="quantityQuotation" hidden={quantityQuotationHidden}>
          <TjSegmented
            options={[
              { label: '报量不报价', value: 1 },
              { label: '报量报价', value: 0 },
            ]}
            onChange={(e: any) => {
              const { provinceId }: any = values;
              // const date = moment().add(provinceId === specialProvinceValue ? 2 : 1, 'day');
              const date = moment().add(1, 'day');

              form.setFieldsValue({
                quantityQuotation: e,
                calendarDate: date,
              });
            }}
          />
        </Form.Item>
        <Form.Item name="calendarDate" rules={[{ required: true, message: '请选择时间' }]}>
          <DatePicker format="YYYYMMDD" placeholder="请选择" className={styles.datePicker} />
        </Form.Item>
        <Space size={'middle'}>
          <Button type="primary" htmlType="submit" className={styles.searchBtn}>
            查询
          </Button>
          <Button className={styles.reset} htmlType="reset" onClick={_onReset.run} ghost>
            重置
          </Button>
        </Space>
      </Form>
      <Space size={16} className={styles.explainOption}>
        {values.marketId === 'PHBSX' && (
          <Radio.Group value={saveType} onChange={changeSaveType} buttonStyle="solid">
            <Radio.Button value={1}>交易数据</Radio.Button>
            <Radio.Button value={0}>调度数据</Radio.Button>
          </Radio.Group>
        )}
        <div
          className={provinceOptions.length > 0 ? styles.button : styles.disabledButton}
          onClick={onClick}
        >
          <FileTextOutlined className={styles.buttonLogo} />
          申报总览
        </div>
      </Space>
      <AllIssuePlan visible={visible} onClose={onClose} provinceOptions={provinceOptions} />
    </div>
  );
};

export default Header;
